﻿using System;
using System.Web.SessionState;
using System.Web;
using RedisSessionStore.Configuration;

namespace RedisSessionStore.NoLock
{
	public class RedisNoLockSessionIDManager : RedisSessionConfig, ISessionIDManager
	{
		public string CreateSessionID(HttpContext context)
		{
			//TODO: Improve generation
			return Guid.NewGuid().ToString("N");
		}

		public string GetSessionID(HttpContext context)
		{
			var cookie = context.Request.Cookies.Get(CookieName);
			return cookie != null ? cookie.Value : null;
		}

		public void Initialize() { }

		public bool InitializeRequest(HttpContext context, bool suppressAutoDetectRedirect, out bool supportSessionIDReissue)
		{
			supportSessionIDReissue = false;
			return false;
		}

		public void RemoveSessionID(HttpContext context)
		{
			//TODO: Might be better to set Expired date to cookie
			//TODO: Find out why this is called after SaveSessionID
			//context.Response.Cookies.Remove(CookieName);
		}

		public void SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded)
		{
			HttpCookie cookie = new HttpCookie(CookieName, id);
			cookie.Expires = DateTime.Now.Add(Configuration.Timeout);
			context.Response.Cookies.Add(cookie);

			redirected = false;
			cookieAdded = true;
		}

		public bool Validate(string id)
		{
			return true;
		}
	}
}
